<template>
  <div class="app-container tabs-content">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.blurry"
          clearable
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入用户名或者姓名搜索"
          style="width: 220px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select v-model="query.deptId" clearable size="small" placeholder="公司" class="filter-item" style="width: 160px" @change="crud.toQuery">
          <el-option v-for="item in deptList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.projDiscipline" clearable size="small" placeholder="项目内专业" class="filter-item" style="width: 130px" @change="crud.toQuery">
          <el-option v-for="item in disciplinesList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.roleId" clearable size="small" placeholder="项目角色" class="filter-item" style="width: 130px" @change="crud.toQuery">
          <el-option v-for="item in roleList2" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.status" clearable size="small" placeholder="状态" class="filter-item" style="width: 100px" @change="crud.toQuery">
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="1000px">
        <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="90px" class="uifix-search-dialog">
          <div v-if=" crud.status.add">
            <el-row style="display: flex;">
              <el-col :span="12">
                <el-form-item :label="'未选列表（'+projMemberList.length+'）'" label-width="130px">
                  <el-input v-model="search.blurry" clearable size="small" placeholder="用户名或姓名" style="width: 217px;" @keyup.enter.native="hanleProjMember" />
                  <el-select v-model="search.deptId" clearable size="small" placeholder="公司" class="filter-item" style="width: 217px" @change="hanleProjMember">
                    <el-option v-for="item in deptList" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                  <el-select v-model="search.discipline" clearable size="small" placeholder="专业" class="filter-item" style="width: 217px;margin:10px 0px 10px 0px;" @change="hanleProjMember">
                    <el-option v-for="item in dict.discipline" :key="item.id" :label="item.label" :value="item.value" />
                  </el-select>
                  <el-button size="mini" type="primary" @click="hanleProjMember">搜索</el-button>
                  <el-button size="mini" style="margin-left: 2px;" @click="getreset">重置</el-button>
                  <el-table :data="projMemberList" stripe style="width: 100%;" height="393" @selection-change="checkAll">
                    <el-table-column type="selection" />
                    <el-table-column :show-overflow-tooltip="true" prop="username" label="用户名" sortable />
                    <el-table-column :show-overflow-tooltip="true" prop="nickName" label="姓名" />
                    <el-table-column :show-overflow-tooltip="true" prop="deptName" label="公司" sortable />
                    <el-table-column :show-overflow-tooltip="true" prop="discipline" label="专业" sortable>
                      <template slot-scope="scope">
                        {{ dict.label.discipline[scope.row.discipline] }}
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
              <el-col :span="3" style="width: 80px; padding: 0 10px; display: flex; flex-direction: column; justify-content: center; ">
                <!--穿梭框选中-->
                <div style="display: flex; justify-content: center;">
                  <el-button class="middle-circle" icon="el-icon-arrow-right" :disabled="!leftData.length" size="mini" type="primary" @click="handelSelect" />
                </div>
                <!--穿梭框取消-->
                <div style="display: flex; justify-content: center;">
                  <el-button class="middle-circle" icon="el-icon-arrow-left" :disabled="!rightData.length" size="mini" type="primary" style="margin-top: 10px; margin-left: 0px;" @click="handleRemoveSelect" />
                </div>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="'已选列表（'+selectArr.length+'）'" label-width="130px">
                  <el-table :data="selectArr" stripe style="width: 100%;" height="460" @selection-change="checkRightAll">
                    <el-table-column type="selection" />
                    <el-table-column :show-overflow-tooltip="true" prop="username" label="用户名" width="90" sortable />
                    <el-table-column :show-overflow-tooltip="true" prop="nickName" label="姓名" />
                    <el-table-column :show-overflow-tooltip="true" prop="deptName" label="公司" sortable />
                    <el-table-column :show-overflow-tooltip="true" prop="discipline" label="专业" sortable>
                      <template slot-scope="scope">
                        {{ dict.label.discipline[scope.row.discipline] }}
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-if=" crud.status.edit">
            <div v-if="isView()">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="form.user.username" v-viewinput="isView()" onkeyup="this.value=this.value.replace(/\s+/g, '')" :disabled="crud.form.id!==null||isView()" style="width: 178px" />
              </el-form-item>
              <el-form-item label="姓名" prop="nickName">
                <el-input v-model="form.user.nickName" v-viewinput="isView()" onkeyup="this.value=this.value.replace(/\s+/g, '')" style="width: 178px" :disabled="isView()" />
              </el-form-item>
              <el-form-item label="性别">
                <span>{{ form.user.gender }}</span>
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model.number="form.user.phone" v-viewinput="isView()" onkeyup="this.value=this.value.replace(/\s+/g, '')" style="width: 178px" :disabled="isView()" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.user.email" v-viewinput="isView()" onkeyup="this.value=this.value.replace(/\s+/g, '')" style="width: 178px" :disabled="isView()" />
              </el-form-item>
              <el-form-item label="企微号" prop="wxNo">
                <el-input v-model="form.user.wxNo" v-viewinput="isView()" onkeyup="this.value=this.value.replace(/\s+/g, '')" style="width: 178px" :disabled="isView()" />
              </el-form-item>
              <el-form-item label="公司" prop="dept.id">
                <treeselect
                  v-model="form.user.dept.id"
                  v-viewinput:treeselect="isView()"
                  :disable-branch-nodes="true"
                  :options="depts"
                  :load-options="loadDepts"
                  style="width: 175px"
                  placeholder="选择公司"
                  :disabled="isView()"
                  class="companySty"
                />
              </el-form-item>
              <el-form-item v-if="form.user.site" label="分站点" prop="siteId">
                <el-select v-model="form.user.site.siteId" v-viewinput="isView()" filterable clearable placeholder="请选择" style="width: 178px" :disabled="isView()">
                  <el-option
                    v-for="item in siteList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="岗位" prop="jobName">
                <el-input v-model="form.user.jobName" v-viewinput="true" style="width: 178px" disabled />
              </el-form-item>
              <el-form-item label="专业" prop="discipline">
                <el-select
                  v-model="form.user.discipline"
                  v-viewinput="isView()"
                  style="width: 178px"
                  filterable
                  clearable
                  placeholder="请选择"
                  :disabled="isView()"
                >
                  <el-option
                    v-for="item in dict.discipline"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="内部资质" prop="internalQualification">
                <el-select
                  v-model="form.user.internalQualification"
                  v-viewinput="isView()"
                  style="width: 178px"
                  filterable
                  clearable
                  placeholder="请选择"
                  :disabled="isView()"
                >
                  <el-option
                    v-for="item in dict.internal_qualification"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="执业资格" prop="practiceQualificationDatas">
                <el-select
                  v-model="practiceQualificationDatas"
                  v-viewinput:multselect="isView()"
                  style="width: 460px"
                  multiple
                  placeholder="请选择"
                  :disabled="isView()"
                >
                  <el-option
                    v-for="item in dict.practice_qualification"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item style="margin-bottom: 18px;" label="平台角色" prop="roleDatas" class="star">
                <el-select
                  v-model="roleDatas"
                  v-viewinput:multselect="isView()"
                  style="width: 460px"
                  multiple
                  placeholder="请选择"
                  :disabled="isView()"
                >
                  <el-option
                    v-for="item in roleList"
                    :key="item.name"
                    :disabled="isView()"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="form.enabled" v-viewinput:radio="isView()" :disabled="form.id === user.id||isView()">
                  <el-radio
                    v-for="item in dict.user_status"
                    :key="item.id"
                    :label="item.value"
                  >{{ item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div v-else>
              <el-form-item label="项目内专业" prop="projDiscipline">
                <el-select
                  v-model="projDisciplineDatas"
                  v-defaultSelect="[disciplinesDefaultSelect]"
                  v-viewinput="isView()"
                  style="width: 700px"
                  multiple
                  placeholder="请选择"
                  :disabled="isView()"
                  @remove-tag="deleteProjDiscipline"
                  @change="changeProjDiscipline"
                >
                  <el-option
                    v-for="item in dict.discipline"
                    :key="item.value"
                    :disabled="disciplinesDefaultSelect.some(data=> data === item.value)"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="项目角色" prop="role2" class="star">
                <el-select
                  v-model="roleDatas2"
                  v-defaultSelect="[roleDefaultSelect]"
                  v-viewinput="isView()"
                  style="width: 700px"
                  multiple
                  placeholder="请选择"
                  :disabled="isView()"
                  @remove-tag="deleteRole2"
                  @change="changeRole2"
                >
                  <el-option
                    v-for="item in roleList3"
                    :key="item.name"
                    :disabled="roleDefaultSelect.some(data=> data === item.id)||item.name==='项目经理'"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="isView()" type="button" @click="crud.cancelCU">关闭</el-button>
          <div v-else>
            <el-button @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 310px)" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column :show-overflow-tooltip="true" prop="username" label="用户名" sortable>
          <template slot-scope="scope">
            <el-link type="primary" @click="hanleView(scope.row.resourceId)">{{ scope.row.user?scope.row.user.username:'' }}</el-link>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="勋章" width="130">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content" style="display: flex;gap: 4px;">
                <p v-for="(item,key) in scope.row.medalConfigDtos" :key="key">{{ item.name }}</p>
              </div>
              <div style="overflow: hidden;text-overflow:ellipsis;width: 100%;">
                <img v-for="(item,key) in scope.row.medalConfigDtos" :key="key" style="width: 30px;height: 30px;" :src="iconMap.get(Number(item.icon))">
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="nickName" label="姓名" sortable>
          <template slot-scope="scope">
            <el-link type="primary" @click="hanleView(scope.row.resourceId)">{{ scope.row.user?scope.row.user.nickName:'' }}</el-link>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="deptName" label="公司" sortable>
          <template slot-scope="scope">
            {{ scope.row.user?scope.row.user.dept.name:'' }}
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="岗位" label="岗位">
          <template slot-scope="scope">
            {{ scope.row.user?scope.row.user.jobName:'' }}
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="practiceQualification" label="内部资质">
          <template slot-scope="scope">
            {{ scope.row.user?dict.label.internal_qualification[scope.row.user.internalQualification] :'' }}
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="执业资格" label="执业资格" :formatter="formatQualification" />
        <el-table-column :show-overflow-tooltip="true" prop="专业" label="专业">
          <template slot-scope="scope">
            {{ scope.row.user?dict.label.discipline[scope.row.user.discipline]:'' }}
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="projectDiscipline" label="项目内专业" :formatter="formatDiscipline" sortable />
        <el-table-column :show-overflow-tooltip="true" prop="roles" label="项目角色" :formatter="formatRoles" />
        <el-table-column :show-overflow-tooltip="true" label="状态" align="center" prop="status" width="70">
          <template slot-scope="scope">
            <el-tooltip slot="right" effect="dark" :content="scope.row.status?'禁用':scope.row.hasOwnProperty('isActivateFlag')&&!scope.row.isActivateFlag?'请先激活该项目策划人并添加为项目经理':'激活'" placement="top-start">
              <el-switch
                v-model="scope.row.statusFlag"
                :disabled="scope.row.statusFlag?formatDisabledStatus(scope.row):(formatDisabledStatus(scope.row)||scope.row.hasOwnProperty('isActivateFlag')&&!scope.row.isActivateFlag)"
                @change="changeEnabled(scope.row, scope.row.status)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','project:edit','project:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
              :disabled-dle="formatDisabledDle(scope.row)||!scope.row.delFlag"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import crudProjectResource, { getDiscipline, getProjectRole, projMemberOption, getProjDeptOption, queryNoDelProjResRoleAndDisc } from '@/api/project/humanRes'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import rrOperation from '@brotherCrud/RR.operation'
import crudOperation from '@brotherCrud/CRUD.operation'
import udOperation from '@brotherCrud/UD.operation'
import { mapGetters } from 'vuex'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
import { getSiteList } from '@/api/system/user'
import { getAll } from '@/api/system/role'
import { iconMap } from '@/views/system/medal/config'

let userRoles = []
let userRoles2 = []
let userProjDiscipline = []
let userPracticeQualifications = []

const defaultForm = { resourceId: null, userId: null, projId: null, status: null, createBy: null, updateBy: null, createTime: null, updateTime: null, username: null, nickName: null, gender: '男', email: null, roles: [], jobName: null, dept: { id: null }, phone: null, wxNo: '', siteId: null, discipline: null, internalQualification: null, enabled: 'true', practiceQualification: [], projectDiscipline: [] }
export default {
  name: 'ProjectResource',
  components: { crudOperation, rrOperation, udOperation, Treeselect },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    if (JSON.parse(localStorage.getItem('projectObject')).projId) {
      return CRUD({
        optShow: {
          add: true,
          edit: false,
          del: false,
          download: true,
          reset: true
        }, title: '项目成员', url: 'api/projectResource', idField: 'resourceId', sort: 'resource_id,desc', query: { size: 10000, projId: JSON.parse(localStorage.getItem('projectObject')).projId }, crudMethod: { ...crudProjectResource }})
    }
  },
  dicts: ['practice_qualification', 'internal_qualification', 'discipline', 'user_status'],
  data() {
    return {
      practiceQualificationDatas: [],
      roleDatas: [], // 平台角色多选时使用
      roleDatas2: [], // 项目角色多选时使用
      roleList: [], // 平台角色
      roleList2: [], // 项目角色
      roleList3: [], // 所有角色
      projDisciplineDatas: [], // 项目内专业选时使用
      disciplinesList: [], // 项目内专业
      depts: [],
      projId: null, // 项目id
      siteList: [], // 站点列表
      deptList: [], // 公司列表
      pageType: '', // 页面类型
      searchParam: {},
      projMemberList: [],
      selectArr: [],
      changeArr: [],
      leftData: [], // 左边选中列表数据
      rightData: [], // 右边选中列表数据
      disciplinesDefaultSelect: [], // 项目内专业的默认值
      roleDefaultSelect: [], // 角色的默认值
      editData: {}, // 编辑数据
      search: {
        blurry: '',
        deptId: null,
        discipline: ''
      },
      statusList: [
        { label: '禁用', value: 0 },
        { label: '启用', value: 1 }
      ],
      permission: {
        add: ['admin', 'project:add'],
        edit: ['admin', 'project:edit'],
        del: ['admin', 'project:del'],
        download: ['admin', 'project:download']
      },
      rules: {

      },
      iconMap
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    computeType() {
      return this.coaFlg === '1' ? this.computerForItmType : '1'
    }
  },
  created() {
    if (JSON.parse(localStorage.getItem('projectObject')).projId) {
      this.projId = JSON.parse(localStorage.getItem('projectObject')).projId
      // 获取单位加载
      this.getDepts()
      // 获取项目内专业
      this.hanleDiscipline()
      // 获取项目角色
      this.hanleProjRole()
      // 取得公司列表
      this.hanleDeptList()
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.practiceQualificationDatas = []
      this.roleDatas = []
      this.roleDatas2 = []
      this.projDisciplineDatas = []
      this.disciplinesDefaultSelect = []
      this.selectArr = []
      this.disciplinesDefaultSelect = []
      this.roleDefaultSelect = []
      // 查询项目成员
      this.hanleProjMember()
    },
    // 初始化编辑时候
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.editData = form
      const _this = this
      this.roleDatas = []
      userRoles = []
      if (form.user && form.user.roles && form.user.roles.length > 0) {
        form.user.roles.forEach(function(role) {
          _this.roleDatas.push(role.id)
          const rol = { id: role.id }
          userRoles.push(rol)
        })
      }

      this.practiceQualificationDatas = []
      userPracticeQualifications = []
      if (form.user && form.user.practiceQualification && typeof (form.user.practiceQualification) === 'string') {
        const practiceQualification = JSON.parse(form.user.practiceQualification)
        practiceQualification.forEach(function(practiceQualification, index) {
          _this.practiceQualificationDatas.push(practiceQualification.id)
          const data = { id: practiceQualification.id }
          userPracticeQualifications.push(data)
        })
      }
      this.roleDatas2 = []
      this.projDisciplineDatas = []
      this.roleDefaultSelect = []
      this.disciplinesDefaultSelect = []
      const params = {
        projId: form.projId,
        userId: form.userId
      }
      queryNoDelProjResRoleAndDisc(params).then(data => {
        if (data) {
          const disciplinesDefaultSelect = data.noDelDisciplines
          const roleDefaultSelect = data.noDelRoleIds
          userRoles2 = []
          if (form.roles && form.roles.length > 0) {
            form.roles.forEach(function(role) {
              if (role.name === '项目经理') {
                roleDefaultSelect.unshift(role.id)
              }
              _this.roleDatas2.push(role.id)
              _this.roleDatas2.sort((a, b) => roleDefaultSelect.indexOf(b) - roleDefaultSelect.indexOf(a))
              const rol = { id: role.id }
              userRoles2.push(rol)
            })
          }
          if (roleDefaultSelect.length > 0) {
            _this.roleDefaultSelect = roleDefaultSelect
          }

          userProjDiscipline = []
          let projDiscipline = []
          if (typeof (form.projectDiscipline) === 'string' && form.projectDiscipline) {
            projDiscipline = JSON.parse(form.projectDiscipline)
            projDiscipline.forEach(function(item) {
              _this.projDisciplineDatas.push(item.id)
              _this.projDisciplineDatas.sort((a, b) => disciplinesDefaultSelect.indexOf(b) - disciplinesDefaultSelect.indexOf(a))
              const i = { id: item.id }
              userProjDiscipline.push(i)
            })
          }
          if (disciplinesDefaultSelect.length > 0) {
            _this.disciplinesDefaultSelect = disciplinesDefaultSelect
          }
        }
      })
    },
    [CRUD.HOOK.afterDelete](crud, form, type) {
      this.$emit('noticeRefresh')
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form, type) {
      // 获取所有项目角色
      this.getRoleList(2)
      this.pageType = ''
      if (form.resourceId) {
        // 查看时
        if (type === 'view') {
          this.pageType = type
          this.hanleSiteList()// 获取站点列表
          this.getSupDepts(form.user.dept.id)
          this.getRoleList(1)// 获取平台角色
        }
      }
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud, form) {
      if (crud.form.resourceId === null) {
        if (this.selectArr.length === 0) {
          this.$message({
            message: '至少选择一条项目成员数据',
            type: 'warning'
          })
          return false
        }
        const resources = []
        this.selectArr.map(item => {
          resources.push({
            userId: item.id,
            projId: this.projId
          })
        })
        crud.form = resources
      } else {
        if (this.roleDatas2.length === 0) {
          this.$message({
            message: '请选择项目角色',
            type: 'warning'
          })
          return false
        }
        crud.form = {}
        Object.assign(crud.form, this.editData)
        crud.form.roles = userRoles2
        crud.form.projectDiscipline = JSON.stringify(userProjDiscipline)
        this.form = crud.form
      }
    },
    // 提交之后
    [CRUD.HOOK.afterSubmit]() {
      // 获取项目内专业
      this.hanleDiscipline()
      // 获取项目角色
      this.hanleProjRole()
      this.$emit('noticeRefresh')
    },
    /* 设置当前行是否可选*/
    selectable(row) {
      const result = row.roles.some(item => {
        if (item.name === '项目经理' || !row.delFlag) {
          return true
        }
      })
      return !result
    },
    // 是否查看
    isView() {
      if (this.pageType === 'view') {
        return true
      } else {
        return false
      }
    },
    // 查看
    hanleView(resourceId) {
      this.crud.data.map((item, index) => {
        if (item.resourceId === resourceId) {
          this.crud.toView(this.crud.data[index], 'view')
        }
      })
    },
    getDepts() {
      getDepts({ enabled: true, isExternal: false }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getSupDepts(deptId) {
      if (deptId) {
        getDeptSuperior(deptId).then(res => {
          const date = res.content
          this.buildDepts(date)
          this.depts = date
        })
      }
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据 主承接
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id, isExternal: false }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 获取公司列表
    hanleDeptList() {
      const params = {
        projId: this.projId
      }
      getProjDeptOption(params).then(data => {
        if (data) {
          this.deptList = data.map(object => {
            return {
              value: object.id,
              label: object.label
            }
          })
        }
      })
    },
    // 获取项目内专业
    hanleDiscipline() {
      const params = {
        projId: this.projId
      }
      getDiscipline(params).then(data => {
        if (data) {
          this.disciplinesList = data.map(object => {
            return {
              value: object.value,
              label: object.label
            }
          })
        }
      })
    },
    // 获取项目角色
    hanleProjRole() {
      const params = {
        projId: this.projId
      }
      getProjectRole(params).then(data => {
        if (data) {
          this.roleList2 = data.map(object => {
            return {
              value: object.id,
              label: object.name
            }
          })
        }
      })
    },
    // 格式化专业
    formatDiscipline(row) {
      const projectDisciplineList = row.projectDiscipline ? JSON.parse(row.projectDiscipline) : []
      if (projectDisciplineList.length > 0) {
        let projectDiscipline = ''
        projectDisciplineList.forEach(item => {
          if (projectDiscipline !== '') {
            projectDiscipline = projectDiscipline + '，' + this.dict.label.discipline[item.id]
          } else {
            projectDiscipline = this.dict.label.discipline[item.id]
          }
        })
        return projectDiscipline
      }
    },
    // 格式化角色
    formatRoles(row) {
      let role = ''
      row.roles.forEach(item => {
        if (role !== '') {
          role = role + '，' + item.name
        } else {
          role = item.name
        }
      })
      return role
    },
    // 格式化disabed delete 是否有项目经理
    formatDisabledDle(row) {
      const result = row.roles.some(item => {
        if (item.name === '项目经理') {
          return true
        }
      })
      return result
    },
    // 格式化disabed status 只有一个项目经理时，该项目经理不可被禁用
    formatDisabledStatus(row) {
      const result = row.roles.some(item => {
        if (item.name === '项目经理' && row.statusFlag === true) {
          return true
        }
      })
      let num = 0
      let result2 = false
      this.crud.data.map(data => {
        data.roles.map(item => {
          if (item.name === '项目经理' && data.statusFlag === true) {
            num++
          }
        })
      })
      if (num <= 1) {
        result2 = true
      } else {
        result2 = false
      }
      return result && result2
    },
    // 格式化执业资格
    formatQualification(row) {
      const qualificationsList = row.user.practiceQualification ? JSON.parse(row.user.practiceQualification) : []
      if (qualificationsList.length > 0) {
        let qualification = ''
        qualificationsList.forEach(item => {
          if (qualification !== '') {
            qualification = qualification + '，' + this.dict.label.practice_qualification[item.id]
          } else {
            qualification = this.dict.label.practice_qualification[item.id]
          }
        })
        return qualification
      }
    },
    // 获取站点列表
    hanleSiteList() {
      getSiteList({}).then(data => {
        if (data) {
          this.siteList = data.map(object => {
            return {
              value: object.siteId,
              label: object.name
            }
          })
        }
      })
    },
    // 获取弹窗内平台角色数据
    getRoleList(i) {
      // type 1平台   2项目
      const params = {
        type: i
      }
      getAll(params).then(res => {
        if (i === 1) {
          this.roleList = res
        }
        if (i === 2) {
          this.roleList3 = res
        }
      }).catch(() => { })
    },
    deleteRole2(value) {
      userRoles2.forEach(function(data, index) {
        if (data.id === value) {
          userRoles2.splice(index, value)
        }
      })
    },
    changeRole2(value) {
      userRoles2 = []
      value.forEach(function(data, index) {
        const role = { id: data }
        userRoles2.push(role)
      })
    },
    deleteProjDiscipline(value) {
      userProjDiscipline.forEach(function(data, index) {
        if (data.id === value) {
          userProjDiscipline.splice(index, value)
        }
      })
    },
    changeProjDiscipline(value) {
      userProjDiscipline = []
      value.forEach(function(data) {
        const p = { id: data }
        userProjDiscipline.push(p)
      })
    },
    checkAll(val) {
      this.leftData = val
    },
    checkRightAll(val) {
      this.rightData = val
    },
    // 穿梭框选中
    handelSelect() {
      for (let i = 0; i < this.selectArr.length; i++) {
        for (let j = 0; j < this.leftData.length; j++) {
          if (this.leftData[j].id === this.selectArr[i].id) {
            this.leftData = []// 避免左边勾选内容leftData与右边内容selectArr重复
          }
        }
      }
      this.selectArr = this.handleConcatArr(this.selectArr, this.leftData)
      this.handleRemoveTabList(this.leftData, this.projMemberList)
      this.leftData = []
    },
    // 穿梭框取消
    handleRemoveSelect() {
      this.projMemberList = this.handleConcatArr(this.projMemberList, this.rightData)
      this.handleRemoveTabList(this.rightData, this.selectArr)
      this.rightData = []
    },
    handleConcatArr(selectArr, leftData) {
      let arr = []
      arr = arr.concat(selectArr, leftData)
      return arr
    },
    handleRemoveTabList(isNeedArr, originalArr) {
      if (isNeedArr.length && originalArr.length) {
        for (let i = 0; i < isNeedArr.length; i++) {
          for (let k = 0; k < originalArr.length; k++) {
            if (isNeedArr[i]['id'] === originalArr[k]['id']) {
              originalArr.splice(k, 1)
            }
          }
        }
      }
    },
    // 查询项目成员
    hanleProjMember() {
      const params = {
        projId: this.projId
      }
      if (this.search.blurry) {
        params.blurry = this.search.blurry
      }
      if (this.search.deptId) {
        params.deptId = this.search.deptId
      }
      if (this.search.discipline) {
        params.disciplines = this.search.discipline
      }
      projMemberOption(params).then(data => {
        this.projMemberList = []
        if (data) {
          const projMemberList = data.map(object => {
            return {
              username: object.username, // 用户名
              nickName: object.nickName, // 姓名
              deptName: object.dept.name, // 公司
              discipline: object.discipline, // 专业
              id: object.id// id
            }
          })
          if (this.selectArr.length <= 0) {
            this.projMemberList = projMemberList
          } else {
            this.projMemberList = projMemberList.filter((v) => {
              return this.selectArr.every((v1) => {
                return v.id !== v1.id
              })
            })
          }
        }
      })
    },
    getreset() {
      this.resetTemp()
      this.hanleProjMember()
    },
    resetTemp() {
      this.search = {
        blurry: '',
        deptId: null,
        discipline: ''
      }
    },
    // 改变状态
    changeEnabled(data) {
      this.$confirm('此操作将在项目中' + `${data.statusFlag ? '激活' : '禁用'}` + data.user.username + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (data.statusFlag === false) {
          data.status = 0
        }
        if (data.statusFlag === true) {
          data.status = 1
        }
        crudProjectResource.edit(data).then(() => {
          const ifHaveM = this.roleList3.some(item => {
            return item.name === '项目经理'
          })
          if (ifHaveM) {
            this.crud.notify(`${data.statusFlag ? '激活' : '禁用'}` + '成功，请去’项目信息‘中更新启动状态。', CRUD.NOTIFICATION_TYPE.SUCCESS)
          } else {
            this.crud.notify(`${data.statusFlag ? '激活' : '禁用'}` + '成功。', CRUD.NOTIFICATION_TYPE.SUCCESS)
          }
          this.$emit('noticeRefresh')
          this.crud.refresh()
        }).catch(() => {
          this.crud.refresh()
          data.status = !data.status
        })
      }).catch(() => {
        this.crud.refresh()
        data.status = !data.status
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.companySty{
  width: 265px;
  font-size: 14px;
  height: 32px;
  display: inline-block;
  vertical-align: middle;
  margin: 0 3px 10px 0;
}
::v-deep .star>.el-form-item__label:before{
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
</style>
